package com.gowants.pems.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.gowants.pems.aspect.Importance;
import com.gowants.pems.aspect.OperType;
import com.gowants.pems.aspect.ScmsAopLog;
import com.gowants.pems.config.AccessLimit;
import com.gowants.pems.mapper.RegionMapper;
import com.gowants.pems.model.City;
import com.gowants.pems.model.Province;
import com.gowants.pems.model.Region;
import com.gowants.pems.util.DateUtil;
import com.gowants.pems.util.JSONList;
import com.gowants.pems.util.JSONMap;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.UUID;

@RestController
@RequestMapping("/region/")
public class RegionController extends BaseController {

    @Autowired
    private RegionMapper mapper;


    /**
     * 获取区域列表
     * @param page
     * @param limit
     * @param reqData
     * @param req
     * @return
     */
    @RequestMapping(value = "/getList", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "区域列表查看", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap getList(@RequestParam(defaultValue = "1", required = false, value = "page") int page,
                           @RequestParam(defaultValue = "10", required = false, value = "limit") int limit,
                           @RequestParam(defaultValue = "", required = false, value = "reqData") String reqData,
                           HttpServletRequest req)
    {
        if (!isPower("/region/getList.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        JSONMap resultMap = new JSONMap();
        Region record = new Region();
        if (!"".equals(reqData))
        {
            JSONList jsonCondition = getCondition(reqData);

            for (Object cond : jsonCondition) {
                this.buildCondition(cond, record);
            }
        }
        // 设置分页查询信息
        PageHelper.startPage(page, limit);
        List<Region> list = mapper.select(record);
        PageInfo<Region> pageInfo = new PageInfo<Region>(list);
        // 赋值方法
        pageSetData(req, resultMap, page,  limit, pageInfo.getPages(),"", list, pageInfo.getTotal());

        return doResponse(req, "", resultMap);
    }

    @RequestMapping(value = "/getOneRegion", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "区域一条记录检索", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap getOneRegion(String request, HttpServletRequest req){
        Region region=new Region();
        String code ="";
        if (!isPower("/region/getOneRegion.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String id = requestBody.getString("id");
            region = mapper.selectById(id);
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, region);
    }

    @RequestMapping(value = "/saveRegion", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "区域保存", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap saveRegion(String request, HttpServletRequest req){
        if (!isPower("/region/saveRegion.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000036";
        try
        {
            Region record = getRequestBody(request, Region.class);
            int count1 = mapper.checkName(record.getName());
            if(count1 > 0)
            {
                return doResponse(req, "TSMS_0000492", null);
            }
            record.setId(UUID.randomUUID().toString());
            record.setCreateUid(getUserId());
            record.setCreateTime(DateUtil.getDate());
            int exeNum = mapper.insert(record);
            if(exeNum > 0)
            {
                code = "TSMS_0000001";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    }

    @RequestMapping(value = "/editRegion", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "区域修改", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap editRegion(String request, HttpServletRequest req){
        if (!isPower("/region/editRegion.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000053";
        try
        {
            Region record = getRequestBody(request, Region.class);
            int count = mapper.checkNameById(record.getName(),record.getId());
            if(count > 0)
            {
                return doResponse(req, "TSMS_0000492", null);
            }
            int exeNum = mapper.update(record);
            if(exeNum > 0)
            {
                code = "TSMS_0000001";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    }

    /**
     * <删除>
     * @param request
     * @param req
     * @return
     * @remake
     */
    @RequestMapping(value = "/deleteRegion", method = RequestMethod.POST)
    @AccessLimit(seconds = 1, maxCount = 3,needLogin=true) //1秒内 允许请求3次
    @ScmsAopLog(description = "区域删除", opType = OperType.execute, importance = Importance.commonly)
    public JSONMap deleteRegion(String request, HttpServletRequest req)
    {
        if (!isPower("/region/deleteRegion.do"))
        {
            return doResponse(req, "TSMS_0000228");
        }
        String code = "TSMS_0000048";
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String id = requestBody.getString("id");
            int exeNum = mapper.delete(id);
            if(exeNum > 0)
            {
                code = "TSMS_0000050";
            }
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }
        return doResponse(req, code, null);
    }

    private void buildCondition(Object cond, Region record)
    {
        JSONMap condition = JSONMap.parseJSONMap(cond.toString());
        String field = condition.getString("field");
        String keyword = condition.getString("keyword");

        if (StringUtils.isNotEmpty(field) && StringUtils.isNotEmpty(keyword))
        {
            switch (field)
            {
                case "id":
                    record.setId(keyword);
                    break;
                case "name":
                    record.setName(keyword);
                    break;
                case "provinceCode":
                    record.setProvinceCode(keyword);
                    break;
                case "cityCode":
                    record.setCityCode(keyword);
                    break;
            }
        }
    }

    /**
     *
     * @param request
     * @param req
     * @return
     */
    @RequestMapping("getProvince")
    public JSONMap getProvince(String request, HttpServletRequest req){
        String code ="";
        try
        {
            List<Province> list= mapper.selectProvince();
            return doResponse(req, code, list);
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    }

    /**
     * 获取城市
     * @return
     */
    @RequestMapping("getCity")
    public JSONMap getCity(String request, HttpServletRequest req){
        String code ="";
        try
        {
            JSONMap requestBody = getRequestBody(request);
            String provinceCode = requestBody.getString("provinceCode");
            List<City> list= mapper.selectCity(provinceCode);
            return doResponse(req, code, list);
        }
        catch (Exception e)
        {
            code = e.getMessage();
        }

        return doResponse(req, code, null);
    }
    
}
